package com.cndatacom.eweb.dao.impl;

import java.util.List;

import com.cndatacom.eweb.common.PaginationModel;
import com.cndatacom.eweb.common.PaginationSupport;
import com.cndatacom.eweb.dao.IRoleDao;
import com.cndatacom.eweb.model.Role;
import com.cndatacom.eweb.model.UserRole;

public class RoleDao extends PaginationSupport implements IRoleDao {

	public Role addOrUpdateRole(Role role) {
		getHibernateTemplate().saveOrUpdate(role);
		return role;
	}

	public boolean addOrUpdateUserRole(UserRole userRole) {
		getHibernateTemplate().saveOrUpdate(userRole);
		return true;
	}

	public boolean deleteRole(Role role) {
		getHibernateTemplate().delete(role);
		return true;
	}

	public boolean deleteUserRole(UserRole userRole) {
		getHibernateTemplate().delete(userRole);
		return true;
	}

	public PaginationModel getAllRole(int offset, int pageSize, boolean paging) {
		return searchPaginated("select r from Role r order by r.id desc", null, offset, pageSize, paging);
	}

	public PaginationModel getAllRoleUsers(int roleId, int offset, int pageSize) {
		return searchPaginated("select ur from UserRole ur where ur.role.id = ? order by ur.id desc", roleId, offset, pageSize, true);
	}

	public Role getRoleById(int id) {
		return (Role)getHibernateTemplate().get(Role.class, id);
	}

	@SuppressWarnings("unchecked")
	public UserRole getUserRoleByUseridAndRoleid(int userId, int roleId) {
		Object[] params = new Object[]{userId, roleId};
		List userRoleList = getHibernateTemplate().find("select ur from UserRole ur where ur.user.id = ? and ur.role.id = ? order by ur.id desc", params);
		if(userRoleList!=null && userRoleList.size()>=1){
			return (UserRole)userRoleList.get(0);
		}
		return null;
	}

}

